﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using 算法入门.Utils;

namespace 算法入门.Domain.Operations
{
    public class User : INotifyPropertyChanged
    {
        private int _userId;
        private string _userName;
        private int _permVal;
        private string _permDesc;
        private string _persBinDesc;

        /// <summary>
        /// 用户Id
        /// </summary>
        public int UserId
        {
            get => _userId;
            set { _userId = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 用户名称
        /// </summary>
        public string UserName
        {
            get => _userName;
            set { _userName = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 权限值
        /// </summary>
        public int PermVal
        {
            get => _permVal;
            set { _permVal = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 权限中文描述
        /// </summary>
        public string PermDesc
        {
            get => _permDesc;
            set { _permDesc = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 权限二进制描述
        /// </summary>
        public string PersBinDesc
        {
            get => _persBinDesc;
            set { _persBinDesc = value; OnPropertyChanged(); }
        }

        public void RefreshData()
        {
            PersBinDesc = BitOperatorHelp.GetBitStr(this.PermVal);
            StringBuilder sbPersTitle = new StringBuilder();

            string res = string.Empty;

            var allPerms = PermissionHelper.GetAllPermissions();
            if (allPerms.Any() && this.PermVal!=0)
            {
                foreach (var perItem in allPerms)
                {
                    if (PermissionHelper.HasPermission(this.PermVal, (Permission)perItem.PerVal))
                    {
                        sbPersTitle.Append(perItem.PerName + ",");
                    }
                }
                //去掉结尾的逗号
                res = sbPersTitle.ToString().Substring(0, sbPersTitle.Length - 1); 
            }
            else
            {
                res = "无任何权限";
            }

            PermDesc = res;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
